<template>
    <div id="container" style="width: 100%; height: 500px;"></div>
  </template>
  
  <script>
  import { onMounted } from 'vue';
  
  export default {
    name: 'Map',
    setup() {
      onMounted(() => {
        if (window.AMap) {
          console.log("AMap is already loaded, initializing map...");
          initMap(); // 如果 AMap 已经加载，直接初始化地图
        } else {
          console.log("AMap not found, loading map script...");
          // 如果 AMap 未加载，动态加载高德地图脚本
          window.initMap = initMap;  // 把 initMap 暴露为全局函数
          const script = document.createElement('script');
          script.src = `https://webapi.amap.com/maps?v=1.4.15&callback=initMap&key=`;
          script.onerror = () => {
            console.error("Failed to load the AMap script.");
          };
          script.onload = () => {
            console.log("AMap script loaded successfully.");
          };
          document.body.appendChild(script);
        }
      });
  
      // 初始化高德地图
      function initMap() {
        if (!window.AMap) {
          console.error("AMap is still not available.");
          return;
        }
  
        console.log("Initializing map...");
        const map = new window.AMap.Map('container', {
          resizeEnable: true,
          zoom: 12,
          center: [121.40011, 31.210239], // 设置地图中心点
        });
  
        // 创建自定义瓦片图层
        const googleMapLayer = new AMap.TileLayer({
          getTileUrl: `https://shdistrict.eshimin.com/lawMap/[z]/[x]_[y].png`, // 替换为自定义瓦片图层的 URL
          opacity: 1,
          zIndex: 99,
        });
  
        // 输出调试信息，检查瓦片图层是否成功添加
        console.log("Adding custom tile layer...");
        googleMapLayer.setMap(map); // 使用 setMap 来将瓦片图层添加到地图
  
        // 添加地图控件（缩放工具、比例尺等）
        window.AMap.plugin(['AMap.Scale', 'AMap.ToolBar'], function () {
          map.addControl(new window.AMap.ToolBar());
          map.addControl(new window.AMap.Scale());
        });
      }
    }
  };
  </script>
  
  <style scoped>
  #container {
    width: 100%;
    height: 500px;
  }
  </style>
  